<?php
namespace app\common\service;

use app\api;
use app\common\helper\CurlHelper;
use Exception;
use think\Cache;
use tools\WXBizDataCrypt;

class WxService {
    private $appId;
    private $appSecret;

    protected  $curlHelper;

    public function __construct($appId, $appSecret) {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
        $this->curlHelper = new CurlHelper();
    }

    public function getOpenId($code, $encryptedData = null, $iv = null): array
    {
        $sessionData = $this->getSessionKey($code);
        if (!$sessionData || !isset($sessionData['session_key'])) {
            // 处理错误情况
            return ['error' => 'Failed to obtain session key'];
        }

        $userInfo = [
            'openId' => $sessionData['openid'],
            'sessionKey' => $sessionData['session_key']
        ];

        if ($encryptedData && $iv) {
            // 解密电话号码
            $phone = $this->decryptData($encryptedData, $iv, $sessionData['session_key']);
            if ($phone) {
                $userInfo['tel'] = $phone;
            } else {
                // 错误处理
                return ['error' => 'Failed to decrypt data'];
            }
        }

        return $userInfo;
    }

    /**
     * @throws Exception
     */
    private function getSessionKey($code) {
        $url = sprintf('https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code',
            $this->appId, $this->appSecret, $code);
        $response = $this->curlHelper->sendRequest($url);
        return json_decode($response, true);
    }

    private function decryptData($encryptedData, $iv, $sessionKey) {
        $pc = new WXBizDataCrypt($this->appId, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0) {
            $dataArr = json_decode($data, true);
            return $dataArr['purePhoneNumber']; // 或者其它需要的字段
        }
        return null;
    }


    //获取token缓存起来

    /**
     * @throws Exception
     */
    public function DoctorAccessToken($APPID, $APPSECRET){
        //创建请求数据
        $url_token="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$APPID}&secret={$APPSECRET}";
        $data_result = $this->curlHelper->sendRequest($url_token);
        $data_two = json_decode($data_result,TRUE);
        $token = $data_two['access_token'];
        Cache::set('access_token',$token,7150);
        return $token;
    }

    //拿到token获取二维码

    /**
     * @throws Exception
     */
    public function getXcxCode($APPID, $APP_SECRET, $code){
        $access_token=Cache::get('access_token');
        if ($access_token) {
            $accessToken= $access_token;
        }else{
            $accessToken = $this->DoctorAccessToken($APPID,$APP_SECRET);
        }
        $url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
        $data=[
            //'access_token'=>$accessToken,
            'scene'=>$code,
            'page'=>'pages/home/vendor',
            'width'=>430,
            'auto_color'=>false,
            'check_path'=>false,
            'env_version'=>"release",
        ];
        $data=json_encode($data);
        //拿到二维码
        $result = $this->curlHelper->curl_post_https($url,$data);
        //把二维码存到服务器端
        return $this->curlHelper->UploadImageQrCode($result);
    }

}
